<?php declare(strict_types=1);

namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Helper\DbConfigHelper;
use App\Helper\HttpHelper;
use App\Helper\RespHelper;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Support\Traits\StaticInstance;

class LinkcenterService
{

    use StaticInstance;

    #[Inject]
    protected HttpHelper $httpHelper;

    protected string $inletAddress;         // 服务域名
    protected string $appId;                // 服务中台分发的appId
    protected string $appSecret;            // 服务中台分发的appSecret


    public function __construct()
    {
        $this->inletAddress = DbConfigHelper::instance()->getValue('LinkCenter_InletAPI');
        if (empty($this->inletAddress)) {
            throw new BusinessException(ErrorCode::ERR_SERVER, 'link_center_inlet Configure missing!');
        }
        $this->appId = env('LINKCENTER_APP_KEY');
        $this->appSecret = env('LINKCENTER_APP_SECRET');
        if (empty($this->appId) || empty($this->appSecret)) {
            throw new BusinessException(ErrorCode::ERR_SERVER, 'link_center_app Configure missing!');
        }
    }

    protected function genGlobalParams(array &$params): void
    {
        $params['ts'] = time();
        ksort($params);
        $signUnits = [$this->appId];
        foreach ($params as $key => $val) {
            $signUnits[] = "$key=$val";
        }
        $signContent = '[' . implode('][', $signUnits) . ']';
        $cipher = "AES-128-ECB";
        $signature = openssl_encrypt($signContent, $cipher, $this->appSecret, OPENSSL_RAW_DATA);
        $params['app_key'] = $this->appId;
        $params['signature'] = md5(base64_encode($signature));
    }

    public function getWapAuthUrl(string $state): string
    {
        return ltrim($this->inletAddress, '/') . "/web_wx_auth?type=base&app_key={$this->appId}&state=$state";
    }

    public function doRequest(array $data, string $url): array
    {
        $apiAddress = ltrim($this->inletAddress, '/') . $url;
        $this->genGlobalParams($data);
        IS_PROD || stdPrinter()->info('请求参数：' . print_r(['url' => $apiAddress, 'params' => $data], true));
        $resp = $this->httpHelper->get($apiAddress, $data);
        if ($resp['code'] !== 200) {
            return RespHelper::error((string)$resp['message'], $resp['body']);
        }
        return (array)@$resp['json'];
    }

    /**
     * 验证回调签名
     * @param array $params
     * @return bool
     */
    public function validateNotifySig(array $params): bool
    {
        if (empty($params['package']) || empty($params['signature'])) {
            return false;
        }
        ksort($params['package']);
        $needSignStr = $this->appId . "&" . json_encode($params['package']) . "&" . $this->appSecret;
        $serverSign = md5($needSignStr);
        return $serverSign === $params['signature'];
    }

}